package com.fastjars.mybatis.dynamic;

import org.springframework.transaction.TransactionDefinition;

/**
 * DataSourceTransactionManager
 * 读写分离事务操作
 * @author Brant Liu <br> 邮箱：<br>lbf1988@qq.com <br>日期：<br>2018/10/10
 * @version 1.0.0
 */
public class DataSourceTransactionManager extends org.springframework.jdbc.datasource.DataSourceTransactionManager {
    /**
     * 设置数据源。只读事务到读库，读写事务到写库
     * @param transaction
     * @param definition
     */
    @Override
    protected void doBegin(Object transaction, TransactionDefinition definition) {
        boolean readOnly = definition.isReadOnly();
        if(readOnly){
            DBHolder.putDataSource(DBType.SLAVE);
        } else {
            DBHolder.putDataSource(DBType.MASTER);
        }
        super.doBegin(transaction, definition);
    }

    @Override
    protected void doCleanupAfterCompletion(Object transaction) {
        super.doCleanupAfterCompletion(transaction);
        DBHolder.clearDataSource();
    }
}
